/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.gwt.remoteaction.server;

import com.google.code.gwt.remoteaction.client.Action;
import com.google.code.gwt.remoteaction.client.RemoteActionService;
import com.google.inject.name.Named;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * An object for calling a particular action method with arguments extracted
 * from an Action object.
 *
 * @author jgennis
 */
class ActionInvoker {

  protected Class<? extends RemoteActionService> serviceClass;

  protected Class<? extends Action> actionClass;

  protected Method actionMethod;

  protected List<ParameterExtractor> parameterExtractors = new ArrayList<ParameterExtractor>();

  public ActionInvoker(Class<? extends RemoteActionService> serviceClass, Method actionMethod,
      Class<? extends Action> actionClass)
      throws NoSuchActionPropertyException, AmbiguousParameterException {
    if (serviceClass == null)
      throw new IllegalArgumentException("The serviceClass argument may not be null");
    if (actionMethod == null)
      throw new IllegalArgumentException("The actionMethod argument may not be null");
    if (actionClass == null)
      throw new IllegalArgumentException("The actionClass argument may not be null");
    try {
      Method serviceMethod = serviceClass.getMethod(actionMethod.getName(),
          actionMethod.getParameterTypes());
      if (!actionMethod.getReturnType().equals(serviceMethod.getReturnType())) {
        throw new IllegalArgumentException("The actionMethod argument is not a method of " +
            "service class " + serviceClass.getCanonicalName());
      }
    } catch (NoSuchMethodException ex) {
      throw new IllegalArgumentException("The service class " + serviceClass.getCanonicalName() +
          " does not contain a method matching the signature of the actionMethod argument.", ex);
    } catch (SecurityException ex) {
      throw new RuntimeException(ex);
    }
    this.serviceClass = serviceClass;
    this.actionMethod = actionMethod;
    this.actionClass = actionClass;
    initParameterExtractors();
  }

  public Object invokeAction(RemoteActionService service, Action action)
      throws InvocationTargetException {
    if (!serviceClass.isAssignableFrom(service.getClass())) {
      throw new IllegalArgumentException("The service argument is not a " +
          serviceClass.getCanonicalName());
    }
    if (!actionClass.isAssignableFrom(action.getClass())) {
      throw new IllegalArgumentException("The action argument is not a " +
          actionClass.getCanonicalName());
    }
    List<Object> parameters = new ArrayList<Object>();
    for (ParameterExtractor parameterExtractor : parameterExtractors) {
      Object parameter = parameterExtractor.extract(action);
      parameters.add(parameter);
    }
    try {
      return actionMethod.invoke(service, parameters.toArray());
    } catch (IllegalAccessException ex) {
      throw new RuntimeException(ex);
    }
  }

  protected void initParameterExtractors()
      throws NoSuchActionPropertyException, AmbiguousParameterException {
    Class<?>[] parameterTypes = actionMethod.getParameterTypes();
    Annotation[][] parameterAnnotations = actionMethod.getParameterAnnotations();
    for (int i = 0; i < parameterTypes.length; i++) {
      ParameterExtractor parameterExtractor = createParameterExtractor(parameterTypes[i],
          parameterAnnotations[i]);
      parameterExtractors.add(parameterExtractor);
    }
  }

  protected ParameterExtractor createParameterExtractor(Class<?> type, Annotation[] annotations)
      throws NoSuchActionPropertyException, AmbiguousParameterException {
    for (Annotation annotation : annotations) {
      if (annotation instanceof Named) {
        Named named = (Named) annotation;
        String name = named.value();
        return createParameterExtractorByName(name, type);
      }
    }
    return createParameterExtractorByType(type);
  }

  protected ParameterExtractor createParameterExtractorByName(String name, Class<?> type)
      throws NoSuchActionPropertyException {
    try {
      try {
        String getterName = Utils.makeGetterName(name);
        Method method = actionClass.getMethod(getterName);
        if (type.isAssignableFrom(method.getReturnType()))
          return new GetterParameterExtractor(method);
      } catch (NoSuchMethodException ex) {
        // Fall through
      }
      try {
        Field field = actionClass.getField(name);
        if (type.isAssignableFrom(field.getType()))
          return new FieldParameterExtractor(field);
      } catch (NoSuchFieldException ex) {
        // Fall through
      }
    } catch (SecurityException ex) {
      throw new RuntimeException(ex);
    }
    throw new NoSuchActionPropertyException("No property named '" + name + "' of type " + type.
        getCanonicalName() + " in Action class " + actionClass.getCanonicalName() +
        " was found");
  }

  protected ParameterExtractor createParameterExtractorByType(Class<?> type)
      throws AmbiguousParameterException, NoSuchActionPropertyException {
    Map<String, Method> parameterGetters = new HashMap<String, Method>();
    for (Method method : actionClass.getMethods()) {
      String methodName = method.getName();
      if (methodName.startsWith("get") && type.isAssignableFrom(method.getReturnType()))
        parameterGetters.put(methodName, method);
    }
    List<Field> parameterFields = new ArrayList<Field>();
    for (Field field : actionClass.getFields()) {
      String getterMethodName = Utils.makeGetterName(field.getName());
      if (type.isAssignableFrom(field.getType()) &&
          !parameterGetters.containsKey(getterMethodName))
        parameterFields.add(field);
    }
    if (parameterGetters.size() + parameterFields.size() > 1) {
      StringBuilder sb = new StringBuilder();
      sb.append("Multiple getter methods returning " + type.getCanonicalName() + " were found " +
          "in Action class " + actionClass.getCanonicalName() + ":\n");
      for (Method m : parameterGetters.values())
        sb.append("  " + m.toString() + "\n");
      for (Field f : parameterFields)
        sb.append("  " + f.toString() + "\n");
      sb.append("Apply the Guice annotation @Named to the " + type.getCanonicalName() +
          "parameters of action method " + actionMethod.toString() + " to disambiguate.");
      throw new AmbiguousParameterException(sb.toString());
    }
    for (Method m : parameterGetters.values())
      return new GetterParameterExtractor(m);
    for (Field f : parameterFields)
      return new FieldParameterExtractor(f);
    throw new NoSuchActionPropertyException("No properties of type " + type.getCanonicalName() +
        " were found in action class " + actionClass.getCanonicalName() + ".");
  }
}
